﻿#ifndef JZGL_SCENE_H_
#define JZGL_SCENE_H_

#include "JZGLItem.h"

class JZGLView;
class JZGLScene : public QObject
{
    Q_OBJECT

public:
	JZGLScene(QObject *parent = nullptr);
	~JZGLScene();

    void addItem(JZGLItem* item);
    void removeItem(JZGLItem* item);
    void clear();

    QList<JZGLView*> views();
    void addView(JZGLView*view);
    void removeView(JZGLView* view);

    JZGLTriangleItem* addTriangle(QVector3D p1, QVector3D p2, QVector3D p3, QColor c = Qt::white);
    JZGLRectItem* addRect(QVector3D pos, float w, float h, QColor c = Qt::white);
    JZGLBoxItem* addBox(QVector3D pos, float w, float h, float depth, QColor c = Qt::white);
    JZGLLineItem* addLine(QVector3D p1, QVector3D p2, QColor c = Qt::white);
    JZGLTextItem* addText(const QString& text, QColor c = Qt::white);

protected slots:
    void onUpdate();

protected:
    friend JZGLItem;
    friend JZGLView;

    enum {
        MeshIndex,
        LineIndex,
        PointIndex,
    };

    struct ItemData
    {
        ItemData();
        void clear();

        bool changed;
        QVector<VertexData> vertex;
        QVector<uint32_t> meshIndex;        
        QVector<uint32_t> lineIndex;
        QVector<uint32_t> pointIndex;
    };
    
    int addVertex(JZGLItem* item, const QVector<VertexData>& pt_list);
    void addIndex(int type, JZGLItem* item,int start, const QVector<int>& index_list);
    void addLineVertex(JZGLItem* item,const QVector<VertexData>& pt_list, const QVector<int>& index_list);
    void addMeshVertex(JZGLItem* item,const QVector<VertexData>& pt_list, const QVector<int>& index_list);
    void addPointVertex(JZGLItem* item, const QVector<VertexData>& pt_list, const QVector<int>& index_list);
    
    void notifyItemChanged(JZGLItem* item);
    void updateItem(JZGLItem* item);
    void update();

    QTimer *m_updateTimer;
    QVector<JZGLItem*> m_items;
    QMap<JZGLItem*, ItemData> m_itemData;

    QList<JZGLView*> m_views;
    bool m_glBufferChanged;
};

#endif // ! JZGL_SCENE_H_
